/**
 *	流程审核步骤用于Flow
 *	开发者：雨中磐石
 *	地址：www.rockoa.com
 *	日期：2023-07-19
 */

package com.framework.Flow;



import com.framerock.baselib.CLog;
import com.framerock.baselib.Rock;
import com.framerock.baselib.RockList;
import com.framerock.baselib.RockMsg;
import com.framerock.db.DBWhere;
import com.framework.ACore.Model;
import java.util.ArrayList;
import java.util.Map;

/**
 * 流程审核步骤用于Flow
 * */
public class FlowCourse  extends FlowBase{

    private Model courseModel;

    public FlowCourse(Flow flows) {
        super(flows);
        courseModel = Model.get(this.nDb, "flowcourse");
    }

    /**
     * 匹配流程
     * */
    public void pipei(Map<String, String> rs)
    {

    }

    /**
     * 获取步骤列表
     * */
    public ArrayList<Map<String, String>> getCourse()
    {
        String where = DBWhere.start().winto("cid", COMPANYID).wint("fmodeid", mFlow.funitid).wint("status", 1).show();
        ArrayList<Map<String, String>> rows = Model.get(this.nDb, "flowcourse").getAll(where, "*", "`sort`,id asc");
        return rows;
    }

    /**
     * 当前步骤信息
     * */
    public Map<String, String> nowCourse = null;

    /**
     * 下一个步骤信息
     * */
    public Map<String, String> nextCourse = null;

    /**
     * 获取当前的流程信息
     * */
    public RockList getFlowCourse()
    {
        this.nowCourse      = null;
        this.nextCourse     = null;
        RockList rocklist   = RockList.get();
        ArrayList<Map<String, String>> rows = Rock.getMapList();
        rocklist.setDataList(rows);
        int status = mFlow.billStatus();
        if(status == 1 || status == 5)return rocklist;
        String nowcourseid = "",nowchecknameid="",nowcheckname="",allcheckid = "",_nowcheckname="",_nowcheckid="";
        ArrayList<Map<String, String>> courseRows   = getCourse();
        ArrayList<Map<String, String>> logRows      = mFlow.getCourseLog();
        Map<String, String> rs,checkinfo, da,nameinfo,uda;
        int i,ischeck,len = courseRows.size(),xuhao=0;
        Boolean bool;
        for(i=0; i<len;i++){
            rs      = courseRows.get(i);
            if(!checkBool(rs))continue;
            bool    = mFlow.mFlowListener.onFlowCourseJudge(rs);
            if(bool != null && !bool)continue;
            da          = rs;
            da.remove("cid");
            da.remove("fmodeid");
            da.remove("receid");
            da.remove("recename");
            ischeck     = 0;
            _nowcheckname = "";_nowcheckid = "";
            //已经有步骤就不要判断了
            if(nowCourse == null){
                checkinfo   = checkInfo(rs, logRows);
                da.put("isbutong", checkinfo.get("isbutong"));
                ischeck     = Rock.getMapint(checkinfo, "ischeck");
                allcheckid  = Rock.getMapString(checkinfo, "allcheckid");
                _nowcheckname   = Rock.getMapString(checkinfo, "nowcheckname");
                _nowcheckid     = Rock.getMapString(checkinfo, "nowcheckid");
            }

            da.put("ischeck", ischeck+"");
            da.put("isnow", "0");
            da.put("isnext", "0");
            if(ischeck == 0){
                if(Rock.getMapString(rs, "checknamebool").equals("yes")){
                    da.put("checkname", _nowcheckname);
                    da.put("checknameid", _nowcheckid);
                }else{
                    nameinfo = this.getCheckName(rs, 1);
                    da.put("checkname", nameinfo.get("name"));
                    da.put("checknameid", nameinfo.get("id"));
                }
            }
            xuhao++;
            da.put("xuhao", xuhao+"");
            if(nowCourse != null && nextCourse==null){
                da.put("isnext", "1");
                nextCourse = da; //下一步的
            }
            if(ischeck == 0 && nowCourse == null){
                da.put("isnow", "1");
                String mspd = Rock.getMapString(da, "checknameid"),ismycheck = "0";
                if(!Rock.isEmpt(mspd) && Rock.contain(","+mspd+",", ","+mRequest.USEAID+","))ismycheck = "1";
                da.put("ismycheck", ismycheck);//是否我审批
                nowCourse = da;
            }
            rows.add(da);
        }
        if(nowCourse != null){
            nowcourseid     = Rock.getMapString(nowCourse, "id");
            nowchecknameid  = Rock.getMapString(nowCourse, "checknameid");
            nowcheckname    = Rock.getMapString(nowCourse, "checkname");
        }
        uda = Rock.getMap(new String[]{
              "nowcourseid",nowcourseid,
              "nowchecknameid",nowchecknameid,
              "nowcheckname",nowcheckname,
              "allcheckid",allcheckid,
        });
        mFlow.mFlowBase.Bill().updateBill(uda, false);

        rocklist.setMap(uda);
        rocklist.setDataList(rows);
        return rocklist;
    }

    /**
     * 判断步骤是否审批
     * */
    private Map<String, String> checkInfo(Map<String, String> rs, ArrayList<Map<String, String>> logRows)
    {
        int ischeck = 0, len = logRows.size(), i, zt = 0, checkyis = 0,zren = 0,yren=0;
        Map<String, String> logrs, info = Rock.getMap(), da,nameinfo,nameinfos;
        String courseid = Rock.getMapString(rs, "id");
        String checkname = "", checkid = "",ycheckid="",bcheckid="",allcheckid = "",cheid,nowcheckname="",nowcheckid="";
        ArrayList<Map<String, String>> checklog = Rock.getMapList();
        int checkshu = Rock.getMapint(rs, "checkshu");
        for (i = 0; i < len; i++) {
            logrs   = logRows.get(i);
            cheid   = logrs.get("checkid");
            if(!Rock.contain(","+allcheckid+",", ","+cheid+",")){
                if(allcheckid.length() > 0)allcheckid+=",";
                allcheckid += ""+cheid+"";
            }
            if (!courseid.equals(logrs.get("courseid"))) continue;
            zt = Rock.getMapint(logrs, "status");
            checkname += "," + logrs.get("checkname") + "";
            checkid += "," + cheid + "";
            da = Rock.getMap();
            da.put("checkname", logrs.get("checkname"));
            da.put("checkid", cheid);
            da.put("status", logrs.get("status"));
            da.put("statusname", logrs.get("statusname"));
            da.put("statuscolor", logrs.get("statuscolor"));
            checklog.add(da);
            if (zt != 0){
                if(zt == 2){
                    bcheckid += "," + cheid + "";//已审核不同意人的id
                }else {
                    ycheckid += "," + cheid + ""; //已审核同意人的id
                    checkyis++;
                }
            }
        }
        if (!Rock.isEmpt(checkname)) {
            checkname   = checkname.substring(1);
            checkid     = checkid.substring(1);
        }
        if (checkshu == 1 && checkyis > 0)ischeck = 1;

        //需要全部审批或者至少2+人
        int isbutong = 0;
        if(checkshu == 0 || checkshu >= 2){
            nameinfo        = this.getCheckName(rs, 0);
            nameinfos       = Rock.getMap();
            for (Map.Entry<String, String> entry : nameinfo.entrySet()) {
                cheid = entry.getKey();zren++;
                if(!Rock.contain(","+ycheckid+",", ","+cheid+",")){
                    nameinfos.put(cheid, entry.getValue());
                }else{
                    yren++;
                }
            }
            nameinfos       = this.getCheckNames(nameinfos);
            nowcheckname    = nameinfos.get("name");
            nowcheckid      = nameinfos.get("id");
            rs.put("checknamebool", "yes");//说明已经获取了
            if(Rock.isEmpt(nowcheckid)){
                if(checkyis > 0)ischeck = 1;
            }
            if(checkshu >= 2 && yren >= checkshu)ischeck = 1;
            //if(ischeck == 0 && zren - yren >= checkshu-yren)isbutong = 1;//这个复杂了，去掉了
        }

        info.put("isbutong", isbutong+"");//为1的时候当有人审核不同意不用通知提交人
        info.put("checkname", checkname);
        info.put("checknameid", checkid);
        info.put("nowcheckname", nowcheckname);
        info.put("nowcheckid", nowcheckid);
        info.put("ischeck", ischeck+"");
        info.put("allcheckid", allcheckid);
       // info.put("checklog", Json.getListString(checklog)); //审批信息记录
        return info;
    }

    /**
     * 是否需要审批
     * */
    private Boolean checkBool(Map<String, String> rs){
        boolean bool    = true,bools = false;
        String receid   = Rock.getMapString(rs, "receid");
        if(!Rock.isEmpt(receid)){
            bools = mFlow.modelUsera.dept().receidInaid(receid, mFlow.getFieldsval("aid"));
            if(!bools)bool = false;
        }
        //根据条件
        String where   = Rock.getMapString(rs, "where");
        if(!Rock.isEmpt(where))where   = mFlow.getFlowwheres(where);
        if(!Rock.isEmpt(where)){
            int to  = mFlow.mModel.getCount("`id`="+mFlow.mid+" AND "+where+"");
            if(to==0)bool = false;
        }
        return bool;
    }

    /**
     * 读取审批人
     * @param rs 步骤信息
     * @param lx 要求的类型
     * */
    public Map<String, String> getCheckName(Map<String, String> rs, int lx)
    {
        Map<String, String> info,ars;
        info = mFlow.mFlowListener.onFlowCheckName(rs);
        if(info != null)return (lx==1) ? getCheckNames(info) :info;
        info = Rock.getMap();
        String type = Rock.getMapString(rs, "checktype");
        String name = "", nameid = "", nameida[], namea[], val = "";
        if (type.equals("user")) {
            name    = Rock.getMapString(rs, "checkname");
            nameid  = Rock.getMapString(rs, "checknameid");
            namea   = name.split(",");
            nameida = nameid.split(",");
            for (int i = 0; i < nameida.length; i++) {
                val = "";
                if (namea.length > i) val = namea[i];
                if (Rock.isEmpt(val)) {
                    ars = mFlow.modelUsera.getUsera(nameida[i]);
                    val = Rock.getMapString(ars, "name");
                }
                info.put(nameida[i], val);
            }
        } else if (type.equals("super")) {

        }
        return (lx==1) ? getCheckNames(info) :info;
    }

    /**
     * 审核人处理
     * */
    private Map<String, String> getCheckNames(Map<String, String> inrs)
    {
        Map<String, String> info = Rock.getMap();
        String name="",nameid="";int i = 0;
        if(inrs != null)for (Map.Entry<String, String> entry : inrs.entrySet()) {
            if(i>0){ nameid += ",";name += ","; }
            nameid += entry.getKey();name += entry.getValue();i++;
        }
        info.put("name", name);
        info.put("id", nameid);
        return info;
    }

    /**
     * 当前流程的状态
     * */
    public Map<String, String> nowStatus(int zt)
    {
        ArrayList<Map<String, String>> store = statusStore();
        Map<String, String> da = Rock.getMap(),rs;
        String statusname = "",statuscolor = "",coursename = "", checkname="";
        da.put("status", zt+"");
        if(this.nowCourse != null){
            coursename = Rock.getMapString(nowCourse, "name");
            checkname  = Rock.getMapString(nowCourse, "checkname");
        }
        for(int i=0; i<store.size();i++){
            rs = store.get(i);
            if(Rock.getMapint(rs, "value") == zt){
                statusname  = rs.get("name");
                statuscolor = Rock.getMapString(rs, "color");
                break;
            }
        }
        da.put("statusname", statusname);
        da.put("statuscolor", statuscolor);
        da.put("coursename", coursename);
        da.put("checkname", checkname);
        return da;
    }

    /**
     * 审批
     * @param zt 审批状态1,2,3
     * @param sm 审批说明
     * */
     public RockMsg check(int zt, String sm)
     {
         RockMsg rockmsg = new RockMsg();
         this.getFlowCourse();
         Map<String, String> nowse = this.nowCourse,nextse;
         if(nowse == null)return rockmsg.error("当前无步骤");
         if(Rock.getMapint(nowse, "ismycheck") != 1)return rockmsg.error("当前不是你审批");
         String courseid    = nowse.get("id");
         String statusname  = "",statuscolor = "",courseact = Rock.getMapString(nowse, "courseact");
         if(Rock.isEmpt(courseact))courseact = "同意|green,不同意|red,,,,,,,,";
         String acta[]  = courseact.split(",");
         String ztval   = acta[zt-1];
         if(!Rock.isEmpt(ztval)){
             String zta[] = ztval.split("\\|");
             statusname = zta[0];
             if(zta.length > 1)statuscolor = zta[1];
         }
         if(zt == 2 && Rock.isEmpt(sm))return rockmsg.error("动作是"+statusname+"，必须输入说明");

         //之前审批
         Map<String, String> before = mFlow.mFlowListener.onFlowCheckBefore(nowse);
         String msg = Rock.getMapString(before, "msg");
         if(!Rock.isEmpt(msg))return rockmsg.error(msg);

         mFlow.addLog(nowse.get("name"),sm, new String[]{
                 "status", zt+"",
                 "courseid", courseid,
                 "statusname",statusname,
                 "statuscolor",statuscolor
         });

         RockList rocklist = getFlowCourse();//再次匹配流程
         nextse = this.nowCourse;
         Map<String, String> dars = null,blrs = rocklist.getMap();
         blrs.put("nstatus", zt+"");
         int isfinish = 0;
         int isbutong = 0;

         //审批完成了||不同意
         if(nextse == null || (zt == 2 && isbutong==0)){
             dars = Rock.putMap(dars, "status", zt+"");
             blrs.put("status", zt+"");
         }
         if(nextse == null && zt != 2)isfinish = 1;

         if(dars != null)mFlow.mModel.update(dars, mFlow.mid);
         mFlow.mFlowBase.Bill().updateBills(blrs);

         if(zt == 2){
             if(isbutong==0)mFlow.flowTodo(FlowTodo.ACTTYPE_DISSENT, mFlow.getFieldsval("aid"), "", "你提交的["+mFlow.modename+"]单据，["+mRequest.USEANAME+"]处理["+statusname+"]，说明："+sm+"");//不同意的
         }else{
             if(nextse != null && !Rock.equals(courseid, nextse.get("id"))){
                 mFlow.flowTodo(FlowTodo.ACTTYPE_NEXT, nextse.get("checknameid"));//通知下一步
             }
         }

         mFlow.mFlowListener.onFlowCheckAfter(nowse);
         if(isfinish == 1){
             mFlow.flowTodo(FlowTodo.ACTTYPE_FINISH, mFlow.getFieldsval("aid"));
             mFlow.sendTodo(FlowTodo.ACTTYPE_FINISH);
             mFlow.mFlowListener.onFlowCheckFinish();
         }

         return rockmsg.success("checkok");
     }

     /**
      * 获取状态
      * */
     public String getStatus(int zt, String act)
     {
         return "";
     }

     /**
      * 流程状态的数据源
      * */
     public ArrayList<Map<String, String>> statusStore()
     {
         ArrayList<Map<String, String>> rows = Rock.getMapList();
         String statustxt = Rock.getMapString(mFlow.moders, "statustxt");
         if(Rock.isEmpt(statustxt))statustxt = "0|待?处理|blue,1|已审批|green,2|不同意|red,3|其他,4|其他,5|已作废|gray";
         String ztarr[]     = statustxt.split(","),arr1[];
         Map<String, String> da;
         for(int i=0; i<ztarr.length;i++){
             da     = Rock.getMap();
             arr1   = ztarr[i].split("\\|");
             da.put("value", arr1[0]);
             da.put("name", arr1[1]);
             if(arr1.length > 2)da.put("color", arr1[2]);
             rows.add(da);
         }
         return rows;
     }
}
